package example.controller;

import example.model.User;
import example.dao.UserDao;

import java.io.IOException;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 从请求中获取表单参数
        request.setCharacterEncoding("UTF-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        // 创建用户对象
        User user = new User(0,username, password,null);

        UserDao userDao = new UserDao();
        int save = 0;
        try {
            save = userDao.addUser("1","1");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (save > 0) {
//            request.setAttribute("msg","提示:注册成功");
//            request.getRequestDispatcher("index.jsp").forward(request,response);

            response.sendRedirect("index.jsp?msg=" + URLEncoder.encode("提示:注册成功", "UTF-8"));
        } else {
            response.getWriter().println("注册失败~");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.sendRedirect("register.jsp");
    }
}
